﻿using System;
using UnityEngine;
using Object = UnityEngine.Object;

/// <summary>
/// 对资源的封装, 释放策略以后补;
/// </summary>
class ResourceItem : IDisposable
{
    public string loadPath;
    public string assetName;
    public bool disposed = false;
    public ResourceItemCortine loadCortine;
    public Object asset;

    //bundle型资源;
    public WWW www;

    //加载场景使用;
    public AsyncOperation sceneOp;

    //prefab使用;
    public ResourceRequest request;
    public ResourceType rType;

    public float LoadProgress
    {
        get
        {
            switch (rType)
            {
                case ResourceType.Prefab:
                    return request.progress;
                case ResourceType.Bundle:
                    return www.progress;
                case ResourceType.Scene:
                    return sceneOp.progress;
                default:
                    return 1f;
            }
        }
    }

    public ResourceItem(string path)
    {
        loadPath = path;
        rType = ResourceType.Prefab;
        loadCortine = new ResourceItemCortine();
    }

    public ResourceItem(AsyncOperation ao)
    {
        rType = ResourceType.Scene;
        loadCortine = new ResourceItemCortine();
    }

    public ResourceItem(string url, string assetName)
    {
        loadPath = url;
        www = new WWW(url);
        this.assetName = assetName;
        rType = ResourceType.Bundle;
        loadCortine = new ResourceItemCortine();
    }

    /// <summary>
    /// 已经实例化过的资源;
    /// </summary>
    Object _instance;
    public Object Instance
    {
        get
        {
            return _instance;
        }
        set
        {
            _instance = value;
        }
    }

    public T Instantiate<T>() where T : Object
    {
        if (_instance == null)
        {
            if (asset != null && asset is T)
            {
                Instance = Object.Instantiate(asset);
                return (T)Instance;
            }
            else
                Debug.LogWarning("asset not match TYPE, can not instantiate");
        }
        else
            Debug.LogWarning("instance has already exist, you could instantiate and manage more instances by your self");

        Debug.LogWarning("instantiate failure");
        return null;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    /// <summary>
    /// 严重注意, 终接器不在主线程调用;
    /// </summary>
    ~ResourceItem()
    {
        Dispose(false);
    }

    public void Dispose(bool disposing)
    {
        if (disposed)
            return;

        //托管资源清理;
        if (disposing)
        {
            if (_instance != null)
                Object.Destroy(_instance);

            _instance = null;
            asset = null;
        }

        //非托管资源清理;
        disposed = true;
    }
}
